import { incrementStarCount, decrementStarCount } from '~/server/database/services/topicService'

export default defineEventHandler(async (event) => {
  try {
    const id = getRouterParam(event, 'id')
    const body = await readBody(event)
    
    if (!id || isNaN(parseInt(id))) {
      throw createError({
        statusCode: 400,
        statusMessage: '无效的题目ID'
      })
    }

    const { action } = body // 'increment' 或 'decrement'

    if (!action || !['increment', 'decrement'].includes(action)) {
      throw createError({
        statusCode: 400,
        statusMessage: '无效的操作类型'
      })
    }

    // 执行收藏操作
    let topic
    if (action === 'increment') {
      topic = await incrementStarCount(parseInt(id))
    } else {
      topic = await decrementStarCount(parseInt(id))
    }

    if (!topic) {
      throw createError({
        statusCode: 404,
        statusMessage: '题目不存在'
      })
    }

    return {
      success: true,
      data: topic,
      message: action === 'increment' ? '收藏成功' : '取消收藏成功'
    }
  } catch (error) {
    console.error('收藏操作失败:', error)
    
    if (error && typeof error === 'object' && 'statusCode' in error) {
      throw error
    }
    
    throw createError({
      statusCode: 500,
      statusMessage: '收藏操作失败'
    })
  }
})
